package com.mairuide.bill.utils;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

public class DownloadUtils {
    public static void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException {
        response.setContentType("application/octet-stream");
        returnName = URLEncoder.encode(returnName, "UTF-8");
        response.addHeader("Content-Disposition","attachment;filename="+new String(returnName.getBytes("ISO8859-1")));
        response.setContentLength(byteArrayOutputStream.size());
        response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
        ServletOutputStream outputstream = response.getOutputStream();	//取得输出流
        byteArrayOutputStream.writeTo(outputstream);					//写到输出流
        byteArrayOutputStream.close();									//关闭
        outputstream.flush();											//刷数据
    }
    /**
     * @Author 刘中华
     * @Date 2019/2/25 20:50
     * @Param [response, zip, zipfileName, dir]
     * @return void
     * @Description  需要response响应  zip是zip文件  zipName是下载的zip名字  dir是暂时的文件目录
     **/
    public static void downFileByStream(HttpServletResponse response, File zip, String zipfileName, File dir){
        FileInputStream inStream=null;
        try {
            setResponseHeader(response,zipfileName);
            inStream = new FileInputStream(zip);
            byte[] buf = new byte[4096];
            int readLength;
            while (((readLength = inStream.read(buf)) != -1)) {
                response.getOutputStream().write(buf, 0, readLength);
            }
            //删除服务器上的文件
            File[] fileList = dir.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                fileList[i].delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /** 设置响应头 */
    public static void setResponseHeader(HttpServletResponse response,String fileName) {
        try {
            response.reset();// 清空输出流
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    + URLEncoder.encode(fileName,"UTF-8")
                    + ".zip");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    //将wb分别写到excel中
    public static File[]  writeExcel(int totalPages, String excelName, List<SXSSFWorkbook> wbs, String path) throws Exception{
        File srcfile[] = new File[totalPages];
        for (int i = 0; i < totalPages; i++) {
            srcfile[i] = new File(path, excelName+i + ".xlsx");
            FileOutputStream fileOutputStream = new FileOutputStream(srcfile[i]);
            SXSSFWorkbook wb = wbs.get(i);
            wb.write(fileOutputStream);
        }
        return srcfile;
    }
    //将wb写到excel中
    public static void  writeExcel2(SXSSFWorkbook wb, String path,String excelName) throws Exception{
        File file = new File(path);
        if(!file.exists()){
            file.mkdir();
        }
        File srcfile = new File(path, excelName + ".xlsx");
        FileOutputStream fileOutputStream = new FileOutputStream(srcfile);
        wb.write(fileOutputStream);
    }

    /**
     * @Author 刘中华
     * @Date 2019/2/25 20:50
     * @Param [response, zip, zipfileName, dir]
     * @return void
     * @Description  需要response响应  zip是zip文件  zipName是下载的zip名字  dir是暂时的文件目录
     **/
    public static void downFileByStream2(HttpServletResponse response, File zip, String zipfileName, String path){
        FileInputStream inStream=null;
        OutputStream out=null;
        try {
            setResponseHeader(response,zipfileName);
            inStream = new FileInputStream(zip);
            byte[] buf = new byte[4096];
            int readLength;
            out=response.getOutputStream();
            while (((readLength = inStream.read(buf)) != -1)) {
                out.write(buf, 0, readLength);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //删除服务器上的文件
                File file = new File(path);
                File[] fileList = file.listFiles();
                for (int i = 0; i < fileList.length; i++) {
                    fileList[i].delete();
                }
                file.delete();
            }

        }
    }
}
